﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Input;
using System.Drawing;
using OpenTK.Graphics;
using Common;

namespace T03.Matrices {
    class MyGameWindow : GameWindow {
        public MyGameWindow() {
            this.Load += MyGameWindow_Load;
            this.Resize += MyGameWindow_Resize;
            this.RenderFrame += MyGameWindow_RenderFrame;
            this.Unload += MyGameWindow_Unload;
            this.Width = 1280;
            this.Height = 720;

        }


        private void MyGameWindow_RenderFrame(object sender, FrameEventArgs e) {
            GL.ClearColor(.1f, .1f, .99f, .9f);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            Render();

            SwapBuffers();
            ProcessEvents();
        }
        Vao vao;
        Shader shader;
        Matrix4 projection, model, view, mvp;
        float[] vertexBufferData = {
        -1.0f, -1.0f, 0.0f,
         1.0f, -1.0f, 0.0f,
         0.0f,  1.0f, 0.0f,
    };
        Vbo vbo;
        VertexAttribManager attribs;
        private void MyGameWindow_Load(object sender, EventArgs e) {

            VSync = VSyncMode.Off;
            GL.Enable(EnableCap.DepthTest);
            //glClearColor(0.0f, 0.0f, 0.4f, 0.0f);


            this.vao = new Vao();
            shader = new Shader("shader.vs", "shader.fs");
            projection = Matrix4.CreatePerspectiveFieldOfView(GLUtility.ToRadians(45f), 4.0f / 3.0f, 0.1f, 100f);
            view = Matrix4.LookAt(new Vector3(4, 3, 3),
                new Vector3(0, 0, 0),
                new Vector3(0, 1, 0));
            model = Matrix4.Identity;
            mvp = model * view * projection;
            vbo = new Vbo(BufferTarget.ArrayBuffer, BufferUsageHint.StaticDraw, vertexBufferData);
            attribs = new VertexAttribManager();
            attribs.AddAttrib(3, vbo, VertexAttribPointerType.Float, false);

        }

        private void Render() {
            shader.Use();
            shader.SetMatrix4("MVP", mvp);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo.Id);
            attribs.Enable();
            GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
            attribs.Disable();
            


        }

        private void MyGameWindow_Resize(object sender, EventArgs e) {
            GL.Viewport(0, 0, Width, Height);
        }



        private void MyGameWindow_Unload(object sender, EventArgs e) {
            shader.Dispose();
            vao.Dispose();
            vbo.Dispose();
        }

    }
}
